import random
from pymt import *
from pyglet.gl import *


#modificar isso aqui para que criemos tambem um selectable object!!!!


class MTConnectableObject(MTRectangularWidget):    
    #construtor
    sizeX = 30
    sizeY = 20
    
    def __init__(self, x,y):
        super(MTConnectableObject, self).__init__(pos=(x,y), size=(self.sizeX,self.sizeY))
        self.selected = False
        # stores if the user is dragging and with which finger
        self.dragging = (False, -1)
    
    def on_draw (self):
        if self.selected:
            glColor3d(1,1,1)
            px,py=self.pos
            px-=self.sizeX/2
            py-=self.sizeY/2
            drawRectangle((px, py), size=(self.sizeX*2,self.sizeY*2))
        super(MTConnectableObject, self).on_draw()    
            
    def select (self):
        self.selected=True
        
    def unselect (self):
        self.selected=False
    
    #will allow the user to drag the object
    def on_touch_move(self, touches, touchID, x, y): 
        super(MTConnectableObject, self).on_touch_move(touches, touchID, x, y)

        isDragging, fingerID = self.dragging
        if isDragging:
            self.x=x
            self.y=y
            
    
    def on_touch_down(self, touches, touchID, x, y): 
        super(MTConnectableObject, self).on_touch_down(touches, touchID, x, y)
        #print "casa_b"
        #unselect the object
        if not self.contains(x, y):
            self.unselect()
            
        if self.selected and self.contains(x, y):
            self.dragging=(True, touchID)
            #print "new (" + str(x) + " "+  str(y)+ ") "
            #print "old " + str(self.pos)
            #self.x=x
            #self.y=y
            
            
    def on_touch_up(self, touches, touchID, x, y): 
        super(MTConnectableObject, self).on_touch_up(touches, touchID, x, y)
        isDragging, fingerID = self.dragging 
        if touchID==fingerID:
            self.dragging=(False, -1)

    #function that returns if this object contains a given point
    def contains (self, x, y):
        if x > self.x and x < (self.x + self.width) and y > self.y and y < (self.y + self.height):
            return True
        else:
            return False
        
    #function that calculates the object's center    
    def calculateCenter(self):
        return (self.x+(self.width/2), self.y+(self.height/2))
    